package com.th.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.th.common.domain.UsSessionToken;
import com.th.common.exception.BaseServiceException;
import com.th.common.utils.DateUtils;
import com.th.common.utils.IdWorker;
import com.th.mapper.UsSessionTokenMapper;
import com.th.service.UsSessionTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import java.util.UUID;

/**
 * @Author tuhang
 * @PackageName nswcy-crowdsource-client-server
 * @Package com.th.service.impl
 * @Date 2023/6/7 16:10
 * @Version 1.0
 */
@Service
@Slf4j
public class UsSessionTokenServiceImpl extends ServiceImpl<UsSessionTokenMapper, UsSessionToken> implements UsSessionTokenService {



    @Override
    public String createToken(Long userId) {
        UsSessionToken usSessionToken = new UsSessionToken();
        usSessionToken.setUserId(userId);

        String token = UUID.randomUUID().toString().replace("-","");
        usSessionToken.setToken(token);
        Date createTime = new Date();
        usSessionToken.setCreateTime(createTime);
        Date expireTime = DateUtils.addMinutes(createTime, 30);
        usSessionToken.setExpireTime(expireTime);

        this.getBaseMapper().insert(usSessionToken);
        return token;
    }

    @Override
    public Boolean renewToken(UsSessionToken usSessionToken) {
        Date expireTime = usSessionToken.getExpireTime();
        //续期
        expireTime = DateUtils.addMinutes(expireTime, 30);
        usSessionToken.setExpireTime(expireTime);

        int i = this.getBaseMapper().updateById(usSessionToken);
        return i > 0;
    }

    @Override
    public UsSessionToken getToken(String token) {
        return this.getBaseMapper().selectOne(UsSessionToken::getToken,token);
    }

    @Override
    public void removeByUserId(Long userId) {
        this.getBaseMapper().delete(new LambdaUpdateWrapper<UsSessionToken>()
                .eq(UsSessionToken::getUserId,userId));
    }
}
